'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'

export default function TestSessionPage() {
  const [sessionInfo, setSessionInfo] = useState<any>(null)
  const [loading, setLoading] = useState(false)

  const checkSession = async () => {
    setLoading(true)
    try {
      // 检查Cookie
      const cookies = document.cookie
      console.log('当前Cookie:', cookies)

      // 测试认证API
      const authResponse = await fetch('/api/auth/me', {
        credentials: 'include'
      })
      const authData = await authResponse.json()
      console.log('认证API响应:', authData)

      // 测试权限API
      const permResponse = await fetch('/api/auth/permissions?tableName=table_c2', {
        credentials: 'include'
      })
      const permData = await permResponse.json()
      console.log('权限API响应:', permData)

      setSessionInfo({
        cookies,
        authResponse: authData,
        permissionsResponse: permData
      })

    } catch (error) {
      console.error('测试失败:', error)
      setSessionInfo({ error: error.message })
    } finally {
      setLoading(false)
    }
  }

  const testLogin = async () => {
    try {
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({ 
          username: 'design', 
          password: 'design123' 
        }),
      })

      const data = await response.json()
      console.log('登录响应:', data)
      
      // 登录后立即检查会话
      setTimeout(checkSession, 1000)
    } catch (error) {
      console.error('登录失败:', error)
    }
  }

  useEffect(() => {
    checkSession()
  }, [])

  return (
    <div className="p-8 space-y-6">
      <h1 className="text-2xl font-bold">会话状态测试</h1>
      
      <div className="flex space-x-4">
        <Button onClick={checkSession} disabled={loading}>
          {loading ? '检查中...' : '检查会话'}
        </Button>
        <Button onClick={testLogin} variant="outline">
          测试登录
        </Button>
      </div>

      {sessionInfo && (
        <Card>
          <CardHeader>
            <CardTitle>会话信息</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div>
                <h4 className="font-medium mb-2">Cookie信息:</h4>
                <pre className="text-xs bg-gray-100 p-2 rounded">
                  {sessionInfo.cookies || '无Cookie'}
                </pre>
              </div>
              
              <div>
                <h4 className="font-medium mb-2">认证API响应:</h4>
                <pre className="text-xs bg-gray-100 p-2 rounded overflow-auto max-h-32">
                  {JSON.stringify(sessionInfo.authResponse, null, 2)}
                </pre>
              </div>
              
              <div>
                <h4 className="font-medium mb-2">权限API响应:</h4>
                <pre className="text-xs bg-gray-100 p-2 rounded overflow-auto max-h-32">
                  {JSON.stringify(sessionInfo.permissionsResponse, null, 2)}
                </pre>
              </div>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
